﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Xml.Linq;
using UFIDA.U9.CusDev.AITPlugInBE;
using UFSoft.UBF.Business;
using UFSoft.UBF.Business.Tool;
using UFSoft.UBF.PL.Engine;
using UFSoft.UBF.PL.ObjectAccess;
using UFSoft.UBF.Util.Log;


namespace UFIDA.U9.CusDev.AITPlugInBP
{
    internal class LogUtils
    {
        //public static ILogger logger = LoggerManager.GetLogger(typeof(ProcessForAIT));
        public static ILogger logger = LoggerManager.GetLogger("AIT");

        public static void Log(string msg)
        {
            logger.Error(msg);
        }

        public static Dictionary<string, object> GetObjectProperties(object obj)
        {
            if (obj == null) return null;

            Dictionary<string, object> dict = new Dictionary<string, object>();
            Type type = obj.GetType();
            PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo property in properties)
            {
                if (property.CanRead) // 确保属性是可读的
                {
                    string propertyName = property.Name;
                    if (IsSysField(propertyName)) continue;
                    object propertyValue = property.GetValue(obj);
                    dict[propertyName] = propertyValue;
                }
            }

            return dict;
        }



        private static bool IsSysField(string propertyName)
        {
            if (propertyName == "InnerData") return true;
            if (propertyName.StartsWith("Res_")) return true;

            return false;
        }

        public static void JsonLog(object obj)
        {
            //插入时记录json文件
            // 判断对象是否实现了 IEnumerable 接口，但排除字符串类型，因为字符串也实现了 IEnumerable<char>
            object json = null;
            String filepath = null;
            if (obj is IEnumerable && !(obj is string))
            {
                //数组,集合
                List<object> list = new List<object>();
                foreach(var item in (IEnumerable)obj)
                {
                    Dictionary<string, object> dict = GetObjectProperties(item);
                    json = JObject.FromObject(dict);
                    list.Add(json);
                    filepath = $"\\log\\{item.GetType().Name}.json";
                }
                json = JArray.FromObject(list);
            }
            else
            {
                //对象
                Dictionary<string, object> dict = GetObjectProperties(obj);
                json = JObject.FromObject(dict);
                filepath = $"\\log\\{obj.GetType().Name}.json";
            }

            
            logger.Error("");
            logger.Error($"===JsonLog=== JSON文件:{filepath}");
            FileUtils.Write(filepath, json.ToString());
        }
    }
}
